import { defineStore } from 'pinia'
import { computed } from 'vue'
import { ref } from 'vue'
import axios from 'axios'
import router from '../router'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)

  const isAuthenticated = computed(() => !!token.value)

  const login = async (credentials) => {
    try {
      const response = await axios.post('/api/login', credentials)
      token.value = response.data.token
      localStorage.setItem('token', token.value)
      // 强制刷新页面以确保状态同步
      window.location.href = '/'
    } catch (error) {
      throw error.response.data
    }
  }

  const register = async (userData) => {
    try {
      const response = await axios.post('/api/register', userData)
      token.value = response.data.token
      localStorage.setItem('token', token.value)
      router.push('/')
    } catch (error) {
      throw error.response.data
    }
  }

  const logout = () => {
    token.value = null
    localStorage.removeItem('token')
    // 强制刷新页面以确保状态同步
    window.location.href = '/login'
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    register,
    logout
  }
})
